<template>
    <div class="app-container">
        <el-row :gutter="20">
            <el-col :span="24" :xs="24">
                <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-edit-outline" size="mini"
                            @click="handleRepair">车辆报修</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-edit-outline" size="mini"
                            @click="handleFee">车辆费用上报</el-button>
                    </el-form-item>
                </el-form>

                <el-row :gutter="10" class="mb8">


                    <!-- <right-toolbar
              :show-search.sync="showSearch"
              :columns="columns"
              @queryTable="getList"
            /> -->
                </el-row>

                <el-table :data="CarList" style="width: 100%" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" />
                    <el-table-column label="车辆图片" prop="carImage" align="center" width="92px">

                        <template slot-scope="scope">
                            <el-image style="width: 80px; height:80px; margin-bottom:-4px;;border-radius: 50%"
                                :src="scope.row.carImage">
                            </el-image>
                        </template>
                    </el-table-column>
                    <el-table-column label="行驶证图片" prop="licenseImage" align="center" width="92px">

                        <template slot-scope="scope">
                            <el-image style="width: 80px; height:80px; margin-bottom:-4px;;border-radius: 50%"
                                :src="scope.row.licenseImage">
                            </el-image>
                        </template>
                    </el-table-column>
                    <el-table-column prop="id" label="车辆ID" align="center" width="170px" />
                    <el-table-column prop="carNumber" label="车牌号" align="center" width="100px" />
                    <el-table-column prop="revenueMethod" label="经营方式" align="center" width="100px" />
                    <el-table-column prop="brand" label="车辆品牌" align="center" width="80px" />
                    <el-table-column prop="carMoney" label="购买金额" align="center" width="80px" />
                    <el-table-column prop="buyTime" label="购置时间" align="center" width="95px" />
                    <el-table-column prop="maxUseYear" label="最大使用年限" align="center" width="110px" />
                    <el-table-column prop="status" label="状态" align="center" width="50px">
                        <template slot-scope="{ row }">
                            <span :style="getStatusStyle(row.status)">{{ row.status }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="driverName" label="司机姓名" align="center" width="80px" />
                    <el-table-column prop="driverPhone" label="司机电话" align="center" width="100px" />
                    <!-- <el-table-column prop="status" label="状态" align="center">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.status"
                  active-value="0"
                  inactive-value="1"
                  @change="handleStatusChange(scope.row)"
                />
              </template>
            </el-table-column> -->


                    <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
                        <template v-if="scope.row.id !== 1" slot-scope="scope">
                            <el-button size="mini" type="text" icon="el-icon-s-finance"
                                @click="handleCarLicense(scope.row)">行驶证详情</el-button>
                            <!-- <el-button size="mini" type="text" icon="el-icon-s-finance"
                  @click="handleDriverLicense(scope.row)">行驶证详情</el-button> -->
                        </template>
                    </el-table-column>
                </el-table>
            </el-col>
        </el-row>


        <!-- 添加或修改参数配置对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="运营费" prop="runFee">
                            <el-input v-model="form.runFee" placeholder="请输入运营费" maxlength="30" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="油费" prop="gasolineFee">
                            <el-input v-model="form.gasolineFee" placeholder="请输入油费" maxlength="11" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>




        <!-- 行驶证配置对话框 -->
        <el-dialog :title="title" :visible.sync="licenseOpen" width="600px" append-to-body>
            <el-form ref="form2" :model="form2" :rules="rules" label-width="80px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="图片" prop="licenseImage">
                            <template v-if="form2.licenseImage != 'default.jpg'">
                                <div>
                                    <el-image v-if="form2.licenseImage" style="width: 400px; height: 260px"
                                        :src="form2.licenseImage" :fit="fit"></el-image>
                                    <button @click="deleteLicenseImage" v-if="form2.licenseImage">删除图片</button>
                                </div>
                            </template>
                            <template v-else-if="form2.licenseImage == 'default.jpg'">
                                <el-upload class="upload-demo" action="http://localhost:8887/api/v1/oss/uploadImg"
                                    :on-preview="handlePreview" :on-remove="handleRemove"
                                    :on-success="handleLicenseImageSuccess" name="img" list-type="picture">
                                    <el-button size="small" type="primary">点击上传</el-button>
                                </el-upload>
                            </template>
                        </el-form-item>
                    </el-col>
                </el-row>


            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="licenseSubmitForm">确 定</el-button>
                <el-button @click="licenseCancel">关 闭</el-button>
            </div>
        </el-dialog>







    </div>
</template>

<script>
import { changeUserStatus, delUser, getUserById, updateUser } from '@/api/system/user';
import { newRepair, getCarFee, saveFee, delCarBasic, getCarLicense, updateLicense, searchCarByToken } from '@/api/system/car';

export default {
    name: 'User',
    data() {
        return {
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,

            },
            title: '',
            // 是否显示弹出层
            open: false,
            // 表单校验
            rules: {
                runFee: [
                    { required: true, message: '运营费不能为空', trigger: 'blur' }
                ],
                gasolineFee: [
                    { required: true, message: '油费不能为空', trigger: 'blur' }
                ],

            },
            // 角色选项
            roleOptions: [],
            // 显示搜索条件
            showSearch: true,
            // 遮罩层
            loading: true,
            // 用户表格数据
            userList: null,
            // 总条数
            total: 0,
            // 选中数组
            ids: [],
            // 表单参数
            form: {},
            form2: {},
            licenseNumber: "",
            email: "",
            status: "",
            revenueMethod: "",
            repairCarNumber: "",
            CarList: []
        }
    },
    watch: {},
    created() {
        this.search(this.licenseNumber, 1, this.queryParams.pageSize);
    },
    methods: {
        getStatusStyle(status) {
            if (status === '运营') {
                return 'color: green;';
            } else {
                return 'color: red;';
            }
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.loading = true;
            this.search(this.licenseNumber, 1, this.queryParams.pageSize);
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        handleRepair() {
            this.$confirm('是否确定进行车辆报修?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const firstCar = this.CarList[0];
                const carNumber = firstCar.carNumber;
                console.log("---------------------------------" + carNumber)
                newRepair(carNumber)
                    .then(response => {
                        // 根据返回结果进行条件判断
                        if (response === '报修成功') {
                            this.$message({
                                type: 'success',
                                message: '报修成功!'
                            });
                            // 报修成功后刷新页面
                            location.reload();
                        } else if (response === '上一阶段维修未结束，不能重复报修') {
                            this.$message({
                                type: 'warning',
                                message: '上一阶段维修未结束，不能重复报修'
                            });
                        }
                    })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消报修'
                });
            });
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        licenseCancel() {
            this.licenseOpen = false
            this.licenseReset()
        },
        /** 查询车辆信息列表 */
        search() {
            console.log("-----------------------------");
            this.loading = true;
            searchCarByToken().then((response) => {
                this.CarList = response.rows;
                this.loading = false;

            });
        },
        // 用户状态修改
        // handleStatusChange(row) {
        //   const text = row.status === '0' ? '启用' : '停用'
        //   this.$modal
        //     .confirm('确认要"' + text + '""' + row.username + '"用户吗？')
        //     .then(function () {
        //       return changeUserStatus(row.id, row.status)
        //     })
        //     .then(() => {
        //       this.$modal.msgSuccess(text + '成功')
        //     })
        //     .catch(function () {
        //       row.status = row.status === '0' ? '1' : '0'
        //     })
        // },
        /** 修改按钮操作 */
        handleFee() {
            const firstCar = this.CarList[0];
            const revenueMethod = firstCar.revenueMethod;
            const carNumber = firstCar.carNumber;
            if (revenueMethod === '挂靠') {
                alert('挂靠车辆不需要进行费用上报');
                return;
            }
            this.reset();
            this.title = '车辆费用上报';
            this.open = true;
            getCarFee(carNumber).then((response) => {
                this.form.runFee = response.runFee;
                this.form.gasolineFee = response.gasolineFee;
            });
        },
        handleCarLicense(row) {
            this.licenseReset()
            this.title = '行驶证详情';
            this.licenseOpen = true;
            getCarLicense(row.id).then((response) => {
                this.form2.id = response.id
                this.form2.licenseImage = response.licenseImage;
                this.licenseImageUrl = response.licenseImage;
                console.log("---------------------------------")
                console.log(response)
            })
        },
        licenseReset() {
            this.licenseImageUrl = undefined,
                this.form2 = {
                    id: undefined,
                    licenseImage: undefined,
                }
            this.resetForm('form2')
        },
        // 表单重置
        reset() {
            this.form = {
                id: undefined,
                runFee: undefined,
                gasolineFee: undefined
            }
            this.resetForm('form')
        },
        /** 新增用户 */
        handleAdd() {
            this.reset();
            // 初始化表单数据
            this.form = {
                phone: '',
                sex: '',
                id: '',
                name: '',
                position: '',
                password: ''
            };
            // 设置对话框标题
            this.title = '添加用户';
            // 打开对话框
            this.open = true;
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = this.ids
            this.$modal
                .confirm('是否确认删除编号为"' + ids + '"的数据项？')
                .then(function () {
                    var i = 0;
                    while (ids[i + 1]) {
                        delCarBasic(ids[i])
                        i = i + 1;
                    }
                    return delCarBasic(ids[i])

                })
                .then(() => {
                    this.queryParams.pageNum = 1;
                    this.search(licenseNumber, 1, this.queryParams.pageSize)
                    this.$modal.msgSuccess('删除成功');
                })
                .catch(() => { })
        },
        Delete(row) {
            this.$modal
                .confirm('是否确认删除编号为"' + row.id + '"的数据项？')
                .then(function () {
                    return delCarBasic(row.id);
                })
                .then(() => {
                    this.queryParams.pageNum = 1;
                    this.search(this.licenseNumber, 1, this.queryParams.pageSize)
                    this.$modal.msgSuccess('删除成功');
                })
                .catch(() => { })
        },
        handleCurrentChange() {
            this.search(this.licenseNumber, this.queryParams.pageNum, this.queryParams.pageSize);
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    this.open = false;
                    const firstCar = this.CarList[0];
                    const carNumber = firstCar.carNumber;
                    saveFee(carNumber, this.form.runFee, this.form.gasolineFee).then((response) => {
                        this.$modal.msgSuccess('上报成功');
                        this.open = false;
                        this.queryParams.pageNum = 1;
                        this.search(this.licenseNumber, 1, this.queryParams.pageSize);
                    });
                }
            });
        },
        licenseSubmitForm: function () {
            this.$refs["form2"].validate((valid) => {
                if (valid) {
                    this.open = false;
                    updateLicense(this.form2.id, this.licenseImageUrl).then((response) => {
                        this.$modal.msgSuccess('成功');
                        this.open = false;
                    });
                }
            });
        },
        handleSuccess(res, file) {
            console.log(res)
            this.carImageUrl = res.data
            sessionStorage.setItem("carImageUrl", this.carImageUrl)
            console.log("------------------------------------" + this.carImageUrl)
            alert(this.carImageUrl)
        },
        handleLicenseImageSuccess(res, file) {
            this.licenseImageUrl = res.data
            alert(this.licenseImageUrl)
        },
        deleteCarImage() {
            // 执行删除图片的逻辑
            this.form.carImage = undefined; // 或者设置为其他的默认值或空字符串
        },
        deleteLicenseImage() {
            this.form2.licenseImage = undefined;
        }
    }
}
</script>